package com.tgy.atomic;

import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * @Author: tgy
 * @Date: 12/9/20 4:30 PM
 */
public class DatabasePool {

    private Connect[] connects;

    private AtomicIntegerArray conStatus;

    private final static int INIT_CAPACITY = 10;

    public DatabasePool(int core) {

        if (core <= 0) {

            core = INIT_CAPACITY;
        }

        connects = new Connect[core];

        for (int i = 0; i < core; i++) {

            connects[i] = new Connect("n" + i);
        }

        conStatus = new AtomicIntegerArray(new int[core]);

    }

    public Connect getConnect() {

        while (true) {

            for (int i = 0; i < connects.length; i++) {

                if (conStatus.get(i) == 0 && conStatus.compareAndSet(i,0,1)) {

                    Connect connect = connects[i];

                    System.out.println(connect + " " + Thread.currentThread().getName() + " 获取");
                    return connect;
                }
            }

            synchronized (this) {

                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    public void backConnent(Connect connect) {

        for (int i = 0; i < connects.length; i++) {

            if (connects[i] == connect) {

                conStatus.set(i,0);
                System.out.println(connect + " " + Thread.currentThread().getName() + " 归还");
                synchronized (this) {

                    this.notifyAll();
                }
            }
        }
    }
}


class Connect{

    private String name;

    public Connect(String name) {
        this.name = name;
    }

    public Connect() {

        this(null);
    }

    @Override
    public String toString() {
        return "Connect{" +
                "name='" + name + '\'' +
                '}';
    }
}
